package com.example.hzq.zqb.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.example.hzq.zqb.R;
import com.example.hzq.zqb.adapter.NetworkImageHolderView;

import com.example.hzq.zqb.bean.CampusShopBean;
import com.example.hzq.zqb.bean.CommentBean;
import com.example.hzq.zqb.bean.GoodsdetailBean;
import com.example.hzq.zqb.bean.ImgsBean;
import com.example.hzq.zqb.model.Model;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.squareup.picasso.Picasso;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import co.lujun.androidtagview.TagContainerLayout;
import co.lujun.androidtagview.TagView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import static com.example.hzq.zqb.adapter.CampusshopAdapter.goodid;
import static com.example.hzq.zqb.fragment.Fragment1.imageurl;

/**
 * Created by hzq on 2017/7/9.
 */

public class ShopdetailActivity  extends AppCompatActivity implements View.OnClickListener,OnItemClickListener{
    private int typeid;
    private ConvenientBanner convenientBanner;//顶部广告栏控件
    private List<String> networkImages= new ArrayList<String>();
    private GoodsdetailBean goodsdetailBean;
    private ImageLoader imageLoader;
    private CampusShopBean campusShopBean;
    private ImageButton back;
    private Button more,buy,buyenter;
    private ImageView goodpic;
    private TextView goodsname,price,goodsdetail,username,usercomment,commenttime,type,p_price,p_count,p_choice;
    private View popview;
    private ImageButton popback,add,sub;
    private PopupWindow popupWindow;
    private EditText num;
   private TagContainerLayout tagContainerLayout;
    private List<String> taglist=new ArrayList<>();
    private boolean tagflag=false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shopdetail);
        init();
        getdate();
        netinit();
        showPopwindow();
    }
    private void init(){
        convenientBanner=(ConvenientBanner)findViewById(R.id.shoppic);
        back=(ImageButton)findViewById(R.id.back1);
        more=(Button)findViewById(R.id.morecomment);
        buy=(Button)findViewById(R.id.tobuy);
        goodsname=(TextView)findViewById(R.id.sd_goodsname);
        price=(TextView)findViewById(R.id.sd_price);
        goodsdetail=(TextView)findViewById(R.id.goodsdetail);
        username=(TextView)findViewById(R.id.cm_username);
        usercomment=(TextView)findViewById(R.id.usercomment);
        commenttime=(TextView)findViewById(R.id.cm_commenttime);
        back.setOnClickListener(this);
        more.setOnClickListener(this);
        buy.setOnClickListener(this);
    }
    private void netinit() {
            imageLoader=ImageLoader.getInstance();
        imageLoader.init(ImageLoaderConfiguration.createDefault(this));
        for(int i=0;i<campusShopBean.getImgs().size();i++){
            networkImages.add(imageurl+campusShopBean.getImgs().get(i).getImg());
        }
        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, networkImages).setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused})
                .setOnItemClickListener(this).startTurning(2000);

    }
    private void getdate(){
        campusShopBean=(CampusShopBean)getIntent().getSerializableExtra("campusshop");
        Model model=new Model();
        Call<List<CommentBean>> call=model.getCommentList(1,goodid);
        call.enqueue(new Callback<List<CommentBean>>() {
            @Override
            public void onResponse(Call<List<CommentBean>> call, Response<List<CommentBean>> response) {
                if(response.isSuccessful()&&response.body()!=null){
                    username.setText(response.body().get(0).getU_id());
                    usercomment.setText(response.body().get(0).getContent());
                    commenttime.setText(response.body().get(0).getCreatetime());
                }
                else
                    Toast.makeText(ShopdetailActivity.this,"获取资源失败",Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onFailure(Call<List<CommentBean>> call, Throwable t) {
                Toast.makeText(ShopdetailActivity.this,"404.comment",Toast.LENGTH_SHORT).show();
            }
        });
        goodsname.setText(campusShopBean.getGoodsname());
        price.setText(campusShopBean.getPrice());
        goodsdetail.setText(campusShopBean.getDetail());
    }
    private void showPopwindow() {
        //加载弹出框的布局
        popview = LayoutInflater.from(ShopdetailActivity.this).inflate(
                R.layout.buypop, null);
        goodpic=(ImageView)popview.findViewById(R.id.pop_pic);
        p_price=(TextView)popview.findViewById(R.id.pop_price);
        p_count=(TextView)popview.findViewById(R.id.pop_count);
        p_choice=(TextView)popview.findViewById(R.id.pop_choice);
        type=(TextView)popview.findViewById(R.id.pop_type);
        popback=(ImageButton)popview.findViewById(R.id.pop_back);
        sub=(ImageButton)popview.findViewById(R.id.sub);
        add=(ImageButton)popview.findViewById(R.id.add);
        num=(EditText)popview.findViewById(R.id.num);
        tagContainerLayout=(TagContainerLayout)popview.findViewById(R.id.goodtag);
        buyenter=(Button)popview.findViewById(R.id.buyenter);
        num.setText("1");
        popupWindow = new PopupWindow(popview,
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);// 取得焦点
        //注意  要是点击外部空白处弹框消息  那么必须给弹框设置一个背景色  不然是不起作用的
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        //点击外部消失
        popupWindow.setOutsideTouchable(true);
        //设置可以点击
        popupWindow.setTouchable(true);
        //进入退出的动画
        popupWindow.setAnimationStyle(R.style.contextMenuAnim);
        //popupWindow隐藏时恢复屏幕正常透明度
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams params=ShopdetailActivity.this.getWindow().getAttributes();
                params.alpha=1f;
                ShopdetailActivity.this.getWindow().setAttributes(params);
            }
        });

        popback.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            p_choice.setText("请选择");
                popupWindow.dismiss();
        }
    });
        sub.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num.setText(Integer.parseInt(num.getText().toString())-1+"");
                if (Integer.parseInt(num.getText().toString())>1){
                    sub.setClickable(true);
                    sub.setImageResource(R.mipmap.minus);
                }
                else {
                    sub.setClickable(false);
                    sub.setImageResource(R.mipmap.minus_dis);
                }
            }
        });
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                num.setText(Integer.parseInt(num.getText().toString())+1+"");
                if (Integer.parseInt(num.getText().toString())>=Integer.parseInt(campusShopBean.getCount())){
                    add.setImageResource(R.mipmap.plus_dis);
                    add.setClickable(false);
                }
                else {
                    sub.setImageResource(R.mipmap.minus);
                    sub.setClickable(true);
                    add.setImageResource(R.mipmap.plus);
                    add.setClickable(true);
                }
            }
        });
        buyenter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (p_choice.getText().toString().equals("请选择")){
                    Toast.makeText(ShopdetailActivity.this,"请选择商品属性",Toast.LENGTH_SHORT).show();
                }
                else  {
                    Intent intent=new Intent();
                    Bundle bundle=new Bundle();
                    intent.setClass(ShopdetailActivity.this,OrderActivity.class);
                    bundle.putSerializable("shopbean",campusShopBean);
                    intent.putExtra("typeid",typeid);
                    intent.putExtra("num",num.getText().toString());
                    intent.putExtra("type",type.getText().toString());
                    intent.putExtras(bundle);
                    startActivity(intent);
                }
            }
        });
        tagContainerLayout.setOnTagClickListener(new TagView.OnTagClickListener() {
            @Override
            public void onTagClick(int position, String text) {
                typeid=position;
                p_choice.setText("已选择:"+text);
            }
            @Override
            public void onTagLongClick(int position, String text) {
            }
        });
    }
    private void tagevent(){
            type.setText(goodsdetailBean.getType().get(0).getName());
            for (int i=0;i<goodsdetailBean.getType().get(0).getLabel().size();i++){
                taglist.add(goodsdetailBean.getType().get(0).getLabel().get(i).getName());
            }
            tagContainerLayout.setTags(taglist);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.back1:
                finish();
                break;
            case R.id.morecomment:
                Intent intent=new Intent();
                intent.setClass(ShopdetailActivity.this,CommentActivity.class);
                startActivity(intent);
                break;
            case R.id.tobuy:
                WindowManager.LayoutParams params=ShopdetailActivity.this.getWindow().getAttributes();
                params.alpha=0.5f;
                ShopdetailActivity.this.getWindow().setAttributes(params);
                popupWindow.showAtLocation(popview, Gravity.BOTTOM, 0, 0);
                Model model=new Model();
                Call<GoodsdetailBean>call=model.getGoodsDetailInfo(goodid);
                call.enqueue(new Callback<GoodsdetailBean>() {
                    @Override
                    public void onResponse(Call<GoodsdetailBean> call, Response<GoodsdetailBean> response) {
                        if(response.isSuccessful()&&response.body()!=null){
                            goodsdetailBean=response.body();
                            if (!tagflag)
                                tagevent();
                            tagflag=true;
                            Picasso.with(ShopdetailActivity.this).load(imageurl+campusShopBean.getHead_img()).placeholder(R.drawable.ic_default_adimage).into(goodpic);
                            p_price.setText("价格：￥"+campusShopBean.getPrice());
                            p_count.setText("库存："+campusShopBean.getCount());
                            type.setText(response.body().getType().get(0).getName());
                        }
                    }

                    @Override
                    public void onFailure(Call<GoodsdetailBean> call, Throwable t) {

                    }
                });
        }
    }

    @Override
    public void onItemClick(int position) {

    }
}
